const http = require('http');
const axios = require('axios');

const serveStatic = require(`serve-static`);
const finalhandler = require(`finalhandler`);
const serve = serveStatic(`dist/build/h5`, {
	index: [`index.html`]
});
const url = require('url');
const querystring = require('querystring');
var foo, bar;
// 创建 HTTP 服务器
async function gotWord(title) {
	const url = `https://dict.youdao.com/m/result?word=${title}&lang=en`;
	try {
		const response = await axios.get(url);
		return response.data;
	} catch (error) {
		console.error('error got url ', error);
		throw error;
	}
}
const server = http.createServer((req, res) => {
	const pathname = url.parse(req.url).pathname;
	var res_data = {
		msg: "ok"
	}
	const cloud = require('../src/db/cloud.js');
	if (pathname == '/foo' && req.method === 'GET') {
		
		res.writeHead(200, {
			'Content-Type': 'application/json'
		});
		res.end(JSON.stringify(res_data));
	}
	if (pathname == '/save' && req.method === 'POST') {
		let body = '';
		req.on('data', chunk => {
			body += chunk.toString();
		});

		req.on('end', () => {
			try {
				const postData = querystring.parse(body);
				console.log('Parsed POST data:', postData);

				res.writeHead(200, {
					'Content-Type': 'application/json'
				});
				cloud({
					type: "save",
					data: JSON.parse(body)
				}).then((rs) => {
					console.log(rs);
					if (rs.errcode == 0)
						res.end(rs.resp_data);
					else
						res.end(res_data)
				})
			} catch (err) {
				res.writeHead(400, {
					'Content-Type': 'application/json'
				});
				res.end(JSON.stringify({
					error: 'Invalid JSON'
				}));
			}
			// res.writeHead(200, 'OK', {
			// 	'Content-type': 'application/json'
			// });
			// cloud({type: "save",data : {
			// 	id : ID,
			// 	content : content
			// }}).then((rs) => {
			// 	console.log(rs);
			// })
			// res.end(res_data)
		});
	}
	if (req.method === 'GET') {
		const params = url.parse(req.url, true).query || {};
		if (pathname == '/word') {
			gotWord(params.title).then((rs) => {
				res.writeHead(200, 'OK', {
					'Content-Type': 'text/html'
				});
				res.end(rs)
			})
		}
		else if (pathname == '/data') {
			res.writeHead(200, 'OK', {
				'Content-type': 'application/json'
			});
			console.log(params);
			if (!foo)
				cloud({}).then((rs) => {
					foo = rs.resp_data
					console.log(foo[0]._id);
					if (!bar)
						cloud({
							db: "dicts"
						}).then((rs) => {
							bar = rs.resp_data
							console.log(bar[0]._id);
							gole()
						})
				})
			else
				gole()

			function gole() {

				if (params.db) {
					res_data = bar
				} else if (params.type) {
					console.log("type : " + params.type);
				} else {
					res_data = foo
				}
				res.end(res_data)
			}

		} else
			serve(req, res, finalhandler(req, res));
	}
});

// 监听端口 80
server.listen(80, () => {
	console.log('Server running at ...');
});